<template>
  <el-dialog
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="false"
    custom-class="mydialog"
    width="1000px"
    title="变更配送费"
    @close="close"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :label-width="formLabelWidth"
      size="small"
      :rules="formRules"
    >
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="配送商名称：">
            <div>{{ serviceDetail.distributeName }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配送产品信息：">
            <my-tooltip
              :is-link="false"
              :content="getProductName(serviceDetail)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配送服务编号：">
            <div>{{ serviceDetail.distributeServeNo }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配送地区：">
            <area-list-view :areas="serviceDetail.region" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="原配送费：">
            <div>
              <div v-if="serviceDetail.computeMode==='固定价格'">
                <span>{{ serviceDetail.distributePrice }}元</span>
                <span>/{{ getLabel('sell_unit',serviceDetail.sellUnit) }}</span>
              </div>
              <div v-if="serviceDetail.computeMode==='终端价百分比'">
                <span>{{ serviceDetail.distributePrice }}%</span>
                <span>终端价</span>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联配送合同：">
            <div>{{ serviceDetail.contractNumber || '无' }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="摘要信息：">
            <div>{{ serviceDetail.distributeAbstract || '无' }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="新配送费："
            :prop="formData.computeMode==='固定价格'?'distributePrice':'distributePercent'"
          >
            <el-row style="margin-bottom: 20px">
              <el-col :span="10">
                <el-radio
                  v-model="formData.computeMode"
                  label="固定价格"
                  value="固定价格"
                  @change="radioChange"
                >固定价格</el-radio>
              </el-col>
              <el-col :span="12">
                <el-radio
                  v-model="formData.computeMode"
                  label="终端价百分比"
                  value="终端价百分比"
                  @change="radioChange"
                >按终端价百分比</el-radio>
              </el-col>
            </el-row>
            <el-row>
              <el-col
                v-if="formData.computeMode==='固定价格'"
                :span="24"
              >
                <el-input
                  v-model="formData.distributePrice"
                  placeholder="请输入配送费"
                  oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
                  @blur="()=>formData.distributePrice = Number(formData.distributePrice)"
                >
                  <template #append><span>元</span><span> / {{ getLabel('sell_unit',serviceDetail.sellUnit) }}</span></template>
                </el-input>
              </el-col>
              <el-col
                v-if="formData.computeMode==='终端价百分比'"
                :span="24"
              >
                <el-input
                  v-model="formData.distributePercent"
                  placeholder="请输入配送费"
                  oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
                  @blur="()=>formData.distributePercent = Number(formData.distributePercent)"
                >
                  <template #append><span>%终端价</span></template>
                </el-input>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="变更原因："
            prop="changeReason"
          >
            <el-input
              v-model="formData.changeReason"
              type="textarea"
              :rows="4"
              placeholder="请输入变更原因"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-checkbox
            v-model="formData.isChangeOther"
            label="同时更新关联配送终端关系中的配送费"
            :value="1"
            :true-label="1"
            :false-label="0"
          />
        </el-col>
      </el-row>
      <el-table
        v-if="formData.isChangeOther === 1"
        ref="multipleTable"
        :data="tableData"
        border
        style="width: 100%"
        :max-height="350"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          :width="55"
          header-align="center"
          align="center"
        />
        <el-table-column
          label="终端名称"
          header-align="center"
          :min-width="160"
          show-overflow-tooltip
        >
          <template #default="scope">{{ scope.row.terminalName }}</template>
        </el-table-column>
        <el-table-column
          label="终端类型"
          header-align="center"
          align="center"
          :min-width="120"
          show-overflow-tooltip
        >
          <template #default="scope">{{ getLabel('app_mode',scope.row.terminalType) }}</template>
        </el-table-column>
        <el-table-column
          prop="terminalPrice"
          label="终端价"
          header-align="center"
          align="center"
          :min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="agentName"
          label="代理商名称"
          header-align="center"
          :min-width="160"
          show-overflow-tooltip
        />
        <el-table-column
          label="当前配送费"
          header-align="center"
          align="center"
          :min-width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div v-if="scope.row.computeMode==='固定价格'">
              <span>{{ scope.row.distributePrice }}</span><span>元</span><span v-if="serviceDetail.sellUnit"> / {{ getLabel('sell_unit', serviceDetail.sellUnit) }}</span>
            </div>
            <div v-if="scope.row.computeMode==='终端价百分比'">
              <span>{{ scope.row.distributePrice }}</span><span>%终端价</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="当前关联配送服务"
          header-align="center"
          prop="distributeServeNo"
          :min-width="160"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新后配送费"
          header-align="center"
          align="center"
          :min-width="140"
          show-overflow-tooltip
        >
          <template #default>
            <div>
              <div v-if="formData.computeMode==='固定价格'">
                <template v-if="formData.distributePrice">
                  <span>{{ formData.distributePrice }}</span><span>元</span><span v-if="serviceDetail.sellUnit"> / {{ getLabel('sell_unit', serviceDetail.sellUnit) }}</span>
                </template>
              </div>
              <div v-if="formData.computeMode==='终端价百分比'">
                <template v-if="formData.distributePercent">
                  <span>{{ formData.distributePercent }}</span><span>%终端价</span>
                </template>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="confirm"
        >提交审批</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  inject,
  reactive,
  ref,
  toRefs,
} from 'vue'

export default defineComponent({
  name: 'ChangeDeliveryPrice',
  emits: ['onsuccess'],
  setup(props, context) {
    const api = inject('api')
    const currentInstance = getCurrentInstance()
    const formRef = ref(null)
    var reactiveData = reactive({
      addOrChange: 'add',
      serviceDetail: {},
      terminalOptions: [],
      formData: {
        distributeId: 0,
        id: 0,
        distributePrice: '',
        distributePercent: '',
        computeMode: '固定价格',
        changeReason: '',
        isChangeOther: 0,
        terminals: [],
      },
      tableData: [],
    })
    const distributePricePass = (rule, value, callback) => {
      if (Number(value) >= 0) {
        if (Number(value) > 0) {
          reactiveData.formData.distributePrice = Number(value)
          callback()
        } else {
          callback(new Error('配送费必须大于0'))
        }
      } else {
        callback(new Error('请输入配送费'))
      }
    }
    const distributePercentPass = (rule, value, callback) => {
      if (Number(value) >= 0) {
        if (Number(value) > 0 && Number(value) < 100) {
          reactiveData.formData.distributePercent = Number(value)
          callback()
        } else {
          callback(new Error('请输入0~100之间的数字'))
        }
      } else {
        callback(new Error('请输入配送费'))
      }
    }
    var formRules = reactive({
      changeReason: [
        { required: true, message: '请输入变更原因', trigger: 'blur' },
      ],
      distributePrice: [
        {
          required: true,
          validator: distributePricePass,
          trigger: 'blur',
        },
        {
          pattern:
            /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
          message: '请输入数字,可保留两位小数',
        },
      ],
      distributePercent: [
        {
          required: true,
          validator: distributePercentPass,
          trigger: 'blur',
        },
      ],
    })
    var formLabelWidth = ref(140)
    var dialogShow = ref(false)
    const getTerminalList = () => {
      var datas = {
        distributeId: reactiveData.serviceDetail.distributeId,
        id: reactiveData.serviceDetail.id,
      }
      api.distributors
        .DISTRIBUTORS_SERVICE_PRICE_TERMINAL(datas)
        .then((res) => {
          if (res.code === 0) {
            reactiveData.tableData = res.data.list || []
          }
        })
    }
    const open = (rowData) => {
      reactiveData.serviceDetail = rowData

      reactiveData.formData.distributeId = rowData.distributeId
      reactiveData.formData.id = rowData.id
      reactiveData.formData.computeMode = rowData.computeMode
      // if (rowData.computeMode === '终端价百分比') {
      //   reactiveData.formData.distributePrice = ''
      //   reactiveData.formData.distributePercent = rowData.distributePrice
      // } else if (rowData.computeMode === '固定价格') {
      //   reactiveData.formData.distributePercent = ''
      //   reactiveData.formData.distributePrice = rowData.distributePrice
      // }
      // 关联终端列表
      getTerminalList()

      dialogShow.value = true
    }
    const close = () => {
      dialogShow.value = false
      formRef.value.resetFields()
    }
    const confirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          if (
            reactiveData.formData.isChangeOther === 1 &&
            reactiveData.formData.terminals.length === 0
          ) {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: '请选择要变更配送费的终端',
            })
            return
          }
          // 元配送费是百分比，不修改直接提交报错
          if (reactiveData.formData.computeMode === '终端价百分比') {
            reactiveData.formData.distributePrice =
              reactiveData.formData.distributePercent
          }
          api.distributors
            .DISTRIBUTORS_SERVICE_PRICE_CHANGE(reactiveData.formData)
            .then((res) => {
              if (res.code === 0) {
                context.emit('onsuccess')
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '已提交审批',
                })
                close()
              } else {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: res.msg,
                })
              }
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    const handleSelectionChange = (val) => {
      reactiveData.formData.terminals = val || []
    }
    return {
      formRef,
      ...toRefs(reactiveData),
      formRules,
      formLabelWidth,
      dialogShow,
      open,
      close,
      confirm,
      handleSelectionChange,
    }
  },
})
</script>
